<template>
    <div style="width: 500px;">
        <i-input v-model="todo" @keypress.native.enter="onenter" placeholder="enter todo"/>
        <todo-item v-for="(item,index) in sortTodos"
                   :key="index"
                   :index="index" :item="item"
                   @delete="onDelete"
                   @done="onDone"/>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { Input } from 'view-design';
import TodoItem from '@/components/TodoItem.vue';
import { TodoType } from '@/utils/types';

@Component({
    components: {
        IInput: Input,
        TodoItem,
    },
})
export default class Home extends Vue {
    todo = '';
    todos: Array<TodoType> = localStorage.todos
        ? JSON.parse(localStorage.todos)
        : [];

    get sortTodos() {
        return this.todos.sort((a, b) => {
            return a.isDone && !b.isDone ? 1 : 0;
        });
    }

    onenter() {
        this.todos.push({
            title: this.todo,
            createTime: Date.now(),
            isDone: false,
        });
        this.todo = '';
    }

    onDelete(index: number) {
        this.todos.splice(index, 1);
    }

    onDone(index: number) {
        this.$set(this.todos[index], 'isDone', true);
    }

    @Watch('todos', {deep: true})
    onTodos() {
        localStorage.setItem('todos', JSON.stringify(this.todos));
    }
}
</script>

<style lang="scss" scoped>

</style>